import React, {useEffect, useMemo, useState} from 'react'
import {
	Form,
	Row,
	Col,
	Input,
	Select,
	Cascader,
	TreeSelect,
	message,
} from 'antd'
import {PageType} from '../constant'
import Styles from './index.less'
import {
	createNo,
	getFirstChannelType,
	getSecondChannelType,
} from '@/service/channel'
import {translateDataToTree} from '@/utils/common'
import {getAllCitysPermission, getCompany} from '@/service/common'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {getDriverPresent} from '@/service/customer/driver'

interface BasicsType {
	pageType: string
	basicsForm: any
	detailRecord: any
	// eslint-disable-next-line react/require-default-props
	user?: any
}
// 城市
const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

// 申请部门与项目申请人
const deptAddUserNames = {
	label: 'name',
	value: 'id',
	key: 'id',
}

const {Option} = Select

export function Basics({pageType, basicsForm, detailRecord, user}: BasicsType) {
	const disabled = pageType === 'detail'

	const [firstChannelType, setFirstChannelType] = useState([])

	const [secondChannelType, setSecondChannelType] = useState([])

	const [citysList, setCitysList] = useState<any[]>([])

	const [orgList, setOrgList] = useState([])

	const [subjectList, setSubjectList] = useState([])

	const [ditchNo, setDitchNo] = useState('')

	const [mainBodyId, setMainBody] = useState() // 主体ID
	const [orgId, setOrgId] = useState() // 公司ID
	const [firstLevel, setFirstLevel] = useState(false)
	const [showDriverId, setShowDriverId] = useState(false)

	const [firstLevelType, setFirstLevelType] = useState('')

	const [secondLevelType, setSecondLevelType] = useState('')

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	const getDitchNo = () => {
		createNo().then((res: any) => {
			if (res?.data) {
				setDitchNo(res.data)
				basicsForm.setFieldValue('ditchNo', res.data)
			}
		})
	}
	// 根据主体id查询公司
	useEffect(() => {
		if (mainBodyId) {
			getCompany({merchantId: mainBodyId}).then((res: any) => {
				if (res?.success) {
					const data = res?.data
					res?.data?.forEach(
						(
							item: {disabled: boolean; type: any},
							index: number,
						) => {
							if (item.type !== 0) {
								data[index].disabled = true
							}
						},
					)
					const list = translateDataToTree(data)
					setOrgList(list as any)
				}
			})
		}
	}, [mainBodyId])
	// 根据公司id查询城市
	useEffect(() => {
		if (orgId) {
			getAllCitysPermission({permission: user?.permissionID, orgId}).then(
				(res: any) => {
					if (res?.data) {
						setCitysList(() => res?.data)
					}
				},
			)
		}
	}, [orgId])

	useEffect(() => {
		getSubjectFun()
		getDitchNo()
	}, [])

	const initialValues = useMemo(() => {
		let value: any = {}
		if (pageType) {
			value = {
				...detailRecord,
				driverId:
					detailRecord?.driverId === 0 ? '' : detailRecord?.driverId,
			}
			setMainBody(value?.subject)
			setOrgId(value?.orgId)

			if (value.channelType) {
				const channelType = value.channelType.split(',')
				if (channelType?.[1] === '3') {
					setFirstLevel(true)
				} else if (channelType?.[1] === '4') {
					setShowDriverId(true)
				}
				value.firstLevelType = channelType[0]
				value.secondLevelType = channelType[1]
				getSecondChannelType({type: value.firstLevelType}).then(
					(res: any) => {
						if (res.success) {
							setSecondChannelType(res.data)
						}
					},
				)
				delete value.channelType
			}
		} else {
			value = {ditchNo}
		}
		setTimeout(() => basicsForm.resetFields(), 1)
		return value
	}, [ditchNo, detailRecord])

	useEffect(() => {
		getFirstChannelType().then((res: any) => {
			if (res.success) {
				// 新增只能增加自营渠道
				const list = res?.data
				const arr: any = []
				list.forEach((res1: any) => {
					if (res1.type === 'Zy_Channel_Type') {
						arr.push(res1)
					}
				})
				setFirstChannelType(arr)
			}
		})
	}, [])

	const firstLevelTypeChange = (type: any) => {
		setFirstLevelType(type)
		setFirstLevel(false)
		basicsForm.setFieldValue('secondLevelType', undefined)
		setSecondLevelType('')
		getSecondChannelType({type}).then((res: any) => {
			if (res.success) {
				setSecondChannelType(res.data)
			}
		})
	}

	const secondLevelTypeOnchange = (e: any) => {
		setSecondLevelType(e)
		if (
			e === '3' &&
			basicsForm.getFieldValue('firstLevelType') === 'Zy_Channel_Type'
		) {
			setFirstLevel(true)
		} else {
			setFirstLevel(false)
		}
		if (
			e === '4' &&
			basicsForm.getFieldValue('firstLevelType') === 'Zy_Channel_Type'
		) {
			setShowDriverId(true)
		} else {
			setShowDriverId(false)
		}
	}

	const onCitysChange = (value: any, selectedOptions: any) => {
		if (value) {
			basicsForm.setFieldsValue({
				cityName: selectedOptions[selectedOptions.length - 1].name,
			})
		}
	}

	const phoneD = useMemo(
		() => !firstLevelType || !secondLevelType,
		[firstLevelType, secondLevelType],
	)

	const getPhone = () => {
		const value = basicsForm.getFieldsValue()
		if (value?.secondLevelType === '4' && value?.phone) {
			getDriverPresent({phone: value?.phone}).then((res: any) => {
				if (res?.data) {
					basicsForm.setFieldsValue({
						driverId: res?.data?.driverId || '',
					})
				} else {
					message.warning('司机联系电话不存在')
					basicsForm.setFieldsValue({
						driverId: '',
					})
				}
			})
		}
	}
	return (
		<div className={Styles.basics}>
			<div className={Styles.titleBox}>基础信息</div>
			<div className={Styles.formBox}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={basicsForm}
					initialValues={initialValues}
					disabled={pageType === PageType.Detail}>
					<Row>
						<Col span={8}>
							<Form.Item
								label="渠道编号"
								name="ditchNo"
								rules={[{required: true}]}>
								<Input placeholder="自动生成" disabled />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="AMC一级渠道类型"
								name="firstLevelType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									onChange={firstLevelTypeChange}>
									{firstChannelType.map((item: any) => (
										<Option value={item.type}>
											{item.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="AMC二级渠道类型"
								name="secondLevelType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									disabled={
										pageType === 'edit'
											? false
											: !firstLevelType
									}
									onChange={secondLevelTypeOnchange}>
									{secondChannelType.map((item: any) => (
										<Option value={item.value}>
											{item.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={8}>
							<Form.Item
								label="渠道名称"
								name="ditchName"
								rules={[{required: true}]}>
								<Input placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="联系电话"
								name="phone"
								rules={[
									{
										required: true,
									},
									{
										pattern: /^[0-9]*$/,
										message: '请输入正确的联系电话',
									},
								]}>
								<Input
									placeholder="请输入"
									disabled={phoneD}
									onBlur={getPhone}
								/>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="身份证"
								name="cardId"
								rules={[
									{
										pattern:
											/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
										message: '请输入正确的身份证',
									},
								]}>
								<Input placeholder={disabled ? '' : '请输入'} />
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={8}>
							<Form.Item
								label="邮箱"
								name="email"
								rules={[
									{
										pattern:
											/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
										message: '请输入正确的邮箱',
									},
								]}>
								<Input placeholder={disabled ? '' : '请输入'} />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="主体"
								name="subject"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									disabled={disabled}
									onChange={(value: any) => {
										setMainBody(value)
										basicsForm.setFieldsValue({
											orgId: undefined,
											cityName: undefined,
										})
									}}>
									{subjectList.map((item: any) => (
										<Option value={item?.id}>
											{item?.merchantName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								label="所属公司"
								name="orgId"
								rules={[{required: true}]}>
								<TreeSelect
									showSearch
									style={{width: '100%'}}
									placeholder="请选择"
									disabled={disabled}
									fieldNames={deptAddUserNames}
									treeDefaultExpandAll
									treeData={orgList}
									onChange={(value) => {
										setOrgId(value)
										basicsForm.setFieldsValue({
											cityName: undefined,
										})
									}}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={8}>
							<Form.Item
								label="城市"
								name="cityId"
								rules={[{required: true}]}>
								<Cascader
									fieldNames={cityNames}
									options={citysList}
									placeholder="请选择"
									disabled={disabled}
									onChange={onCitysChange}
								/>
							</Form.Item>
						</Col>
						{showDriverId && (
							<Col span={8}>
								<Form.Item label="司机ID" name="driverId">
									<Input
										placeholder={disabled ? '' : '请输入'}
										disabled
									/>
								</Form.Item>
							</Col>
						)}

						{firstLevel && (
							<Col span={8}>
								<Form.Item
									label="渠道code码"
									name="code"
									rules={[{required: true}]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
						)}
					</Row>

					<Row>
						<Col span={24}>
							<Form.Item label="描述" name="description">
								<Input.TextArea />
							</Form.Item>
						</Col>
					</Row>
					<Form.Item
						label="1"
						name="cityName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
					<Form.Item
						label="2"
						name="orgName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
					<Form.Item
						label="3"
						name="subjectName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
				</Form>
			</div>
		</div>
	)
}
